<template>
  <Dialog
    v-model="dialogVisible"
    :title="t('instance.differenceSelection.differResultSettingTitle')"
    width="400"
  >
    <div v-if="candidateNames" class="mb-10px">
      <p>{{ t('instance.differenceSelection.settingTips') }}</p>
      <p>{{ candidateNames }}</p>
    </div>
    <el-radio-group v-model="differResult" @change="differLevel = ''">
      <el-radio :value="true">{{ t('common.yes') }}</el-radio>
      <el-radio :value="false">{{ t('common.no') }}</el-radio>
    </el-radio-group>
    <el-input
      v-if="differResult"
      v-model="differLevel"
      :placeholder="
        t('common.inputTextPlaceholder') + t('instance.differenceSelection.differLevel')
      "
      class="mt-10px"
      clearable
    />
    <template #footer>
      <el-button :disabled="loading" type="primary" @click="handleConfirm">{{
        t('common.ok')
      }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { CandidateApi } from '@/api/awards/candidate'
import { FinalWinVO } from '@/api/awards/finalwin'

defineOptions({ name: 'DifferenceConfirm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(false) // 加载中
const finalWinList = ref<FinalWinVO[]>([]) // 差额评选候选人列表
const differResult = ref(true) // 差额评选结果
const differLevel = ref('') // 差额评选等级

const candidateNames = computed(() => {
  return finalWinList.value.map((item) => item.studentName).join('、')
})

// 确认结果
const emits = defineEmits(['success'])
const handleConfirm = async () => {
  // if (differResult.value && !differLevel.value) {
  //   message.error(t('instance.differenceSelection.message.levelRequired'))
  //   return
  // }
  try {
    await message.confirm(t('instance.differenceSelection.message.confirmTips'))
  } catch {
    return
  }
  // console.log(
  //   '差额评选结果:',
  //   finalWinList.value.map((item) => item.id),
  //   differResult.value
  // )
  loading.value = true
  try {
    dialogVisible.value = false
    await CandidateApi.setDiffResult({
      candidateIds: finalWinList.value.map((item) => item.awardsCandidateId),
      isAward: differResult.value,
      diffGrade: differLevel.value
    })
    message.success(t('common.success'))
    emits('success')
  } finally {
    loading.value = false
  }
}

const reset = () => {
  differResult.value = true
  differLevel.value = ''
  finalWinList.value = []
}

/** 打开弹窗 */
const open = (rows: FinalWinVO[]) => {
  reset()
  dialogVisible.value = true
  finalWinList.value = rows
}

defineExpose({ open })
</script>

<style scoped lang="scss"></style>
